package com.start.manager.controller;


import com.start.manager.domain.entity.Goods;
import com.start.manager.domain.vo.GoodsVO;
import com.start.manager.service.IGoodsService;
import com.start.manager.util.PageUtil;
import com.start.manager.util.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Lijian
 * @since 2019-12-20
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IGoodsService goodsService;

    @GetMapping(value = "/getList")
    @ResponseBody
    public ResponseResult getList(@ModelAttribute GoodsVO goodsVO) {
        PageUtil pageUtil = goodsService.findList(goodsVO);
        return ResponseResult.success(pageUtil);
    }

    @PostMapping(value = "/saveGoods")
    @ResponseBody
    public ResponseResult saveGoods(@RequestBody GoodsVO goodsVo) {
        Goods byId = null;
        if (StringUtils.isNotBlank(goodsVo.getId())) {
            byId = goodsService.getById(goodsVo.getId());
        }
        if (byId == null) {
            boolean result = goodsService.saveGoods(goodsVo);
            if (!result) {
                return ResponseResult.error("添加失败");
            }
            return ResponseResult.success("添加成功");
        } else {
            //更新用户操作
            BeanUtils.copyProperties(goodsVo, byId);
            boolean result = goodsService.updateById(byId);
            if (!result) {
                return ResponseResult.error("更新失败");
            }
            return ResponseResult.success("更新成功");
        }

    }

    @DeleteMapping(value = "/deleteGoods/{goodsId}")
    @ResponseBody
    public ResponseResult deleteGoods(@PathVariable String goodsId) {
        boolean result = goodsService.removeById(goodsId);
        if (!result) {
            return ResponseResult.error();
        }
        return ResponseResult.success();
    }

    @PutMapping(value = "/{goodsId}/status/{status}")
    @ResponseBody
    public ResponseResult updateStatus(@PathVariable String goodsId, @PathVariable boolean status) {
        Goods byId = goodsService.getById(goodsId);
        byId.setStatus(status);
        boolean result = goodsService.updateById(byId);
        if (!result) {
            return ResponseResult.error();
        }
        return ResponseResult.success();
    }

}
